package com.deer.wms.base.system.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.deer.wms.base.system.dao.SupplierManageMapper;
import com.deer.wms.base.system.model.Item.ItemInfo;
import com.deer.wms.base.system.model.Item.ItemInfoVo;
import com.deer.wms.base.system.model.Supplier.SupplierManage;
import com.deer.wms.base.system.model.Supplier.SupplierManageCriteria;
import com.deer.wms.base.system.model.Supplier.SupplierManageDto;
import com.deer.wms.base.system.model.Supplier.SupplierManageVo;
import com.deer.wms.base.system.model.erp.ReturnGoods;
import com.deer.wms.base.system.model.http.HttpClientss;
import com.deer.wms.base.system.service.SupplierManageService;
import com.deer.wms.project.root.core.result.CommonCode;
import com.deer.wms.project.root.exception.ServiceException;
import com.deer.wms.project.root.service.SuperServiceImpl;
import com.deer.wms.project.root.util.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * Created by guo on 2019/11/21.
 */
@Service
@Transactional
public class SupplierManageServiceImpl extends SuperServiceImpl<SupplierManageMapper, SupplierManage> implements SupplierManageService {

    @Autowired
    private SupplierManageMapper supplierManageMapper;

    @Autowired
    private RedisUtil redisUtil;

    @Override
    public List<SupplierManageDto> findByCode(String supplierCode) {
        return supplierManageMapper.findByCode(supplierCode);
    }

    @Override
    public List<SupplierManageDto> findByName(String supplierName) {
        return supplierManageMapper.findByName(supplierName);
    }

    @Override
    public List<SupplierManageDto> findList(SupplierManageCriteria criteria) {
        return supplierManageMapper.findList(criteria);
    }


    @Override
    public void deleteBySupplierCode(String supplierCode) {
        supplierManageMapper.deleteBySupplierCode(supplierCode);
    }

    @Override
    public SupplierManage findBy(String field, String value) {
        QueryWrapper<SupplierManage> qw = new QueryWrapper<>();
        return getOne(qw.eq(field, value));
    }

    /**
     * 清空供应商数据
     */
    @Override
    public void clear() {
        baseMapper.clear();
    }

    public boolean save(SupplierManage supplierManage){
        super.save(supplierManage);
        redisUtil.remove("allSupplierManage");
        return true;
    }

    public void deleteById(Integer supplierManageId){
        super.removeById(supplierManageId);
        redisUtil.remove("allSupplierManage");
    }

    public void update(SupplierManage supplierManage){
        super.updateById(supplierManage);
        redisUtil.remove("allSupplierManage");
    }

    /**
     * 往来单位查询
     * @param hashMap 条件
     * @return
     */
    @Override
    public List<SupplierManage> addSupplierManager(Map<String, Object> hashMap) {
        List<SupplierManage> billList = new ArrayList<>();
        Map<String, Object> returnMap = HttpClientss.getDateFromERP2("http://61.160.125.186:5555/zp/api/ZpViewInfo/Query", HttpMethod.POST, hashMap);
        if (returnMap.get("code")!= null && "200".equals(returnMap.get("code"))){
            if (returnMap.get("result")!= null){
                JSONArray jsonArray = JSONArray.parseArray(String.valueOf(returnMap.get("result")));
                billList = JSONObject.parseArray(jsonArray.toJSONString(), SupplierManage.class);
            }else {
                System.out.println("查询ERP单据信息为空！");
                throw new ServiceException(CommonCode.SERVER_INERNAL_ERROR,"查询ERP单据信息为空！");
            }
        }else {
            System.out.println("查询ERP单据信息失败！");
            throw new ServiceException(CommonCode.SERVER_INERNAL_ERROR,"查询ERP单据信息失败！");
        }
        return billList;
    }

    /**
     * 往来单位添加修改
     * @param hashMap
     */
    @Override
    public void saveSupplierManager(Map<String, Object> hashMap) {
        //获取往来单位数据
        List<SupplierManage> supplierManageList = findByCodes(hashMap);
        //获取数据库往来单位
        List<SupplierManage> supplierManages = supplierManageMapper.selectList(new LambdaQueryWrapper<>());
        if (supplierManages.size() == 0){
            //全部添加
            int row = supplierManageMapper.insertList(supplierManageList);
            if (row <= 0) {
                throw new ServiceException(CommonCode.SERVER_INERNAL_ERROR, "添加往来单位失败");
            }
            return;
        }
        //获取往来单位数据的所有供应商编码
        List<String> supplierCodes = new ArrayList<>();
        supplierManages.stream().forEach(t->{
            supplierCodes.add(t.getSupplierCode());
        });

        List<SupplierManage> collect = supplierManageList.stream().filter(t -> supplierCodes.contains(t.getSupplierCode())).collect(Collectors.toList());
        if (collect.size() > 0) {//修改
            int row = supplierManageMapper.updateList(collect);
            if (row <= 0) {
                throw new ServiceException(CommonCode.SERVER_INERNAL_ERROR, "修改往来单位失败");
            }
        }

        List<SupplierManage> coll = supplierManageList.stream().filter(t -> !supplierCodes.contains(t.getSupplierCode())).collect(Collectors.toList());
        if (coll.size() > 0){//新增
            int row = supplierManageMapper.insertList(coll);
            if (row <= 0) {
                throw new ServiceException(CommonCode.SERVER_INERNAL_ERROR, "添加往来单位失败");
            }
        }
    }

    /**
     * 获取往来单位信息
     * @param hashMap 条件
     * @return
     */
    public List<SupplierManage> findByCodes(Map<String,Object> hashMap){
        List<SupplierManageVo> billList = new ArrayList<>();
        List<SupplierManage> list = new ArrayList<>();
        Map<String, Object> returnMap = HttpClientss.getDateFromERP2("http://61.160.125.186:5555/zp/api/ZpViewInfo/Query", HttpMethod.POST, hashMap);
        if (returnMap.get("code")!= null && "200".equals(returnMap.get("code").toString())){
            if (returnMap.get("result")!= null){
                JSONArray jsonArray = JSONArray.parseArray(String.valueOf(returnMap.get("result")));
                billList = JSONObject.parseArray(jsonArray.toJSONString(), SupplierManageVo.class);
                for (SupplierManageVo vo:billList){
                    SupplierManage supplierManage = new SupplierManage();
                    supplierManage.setSupplierCode(vo.getWldwCode());//编码
                    supplierManage.setSupplierName(vo.getWldwName());//名称
                    supplierManage.setWldwType(vo.getWldwType());//类型  ( 0  供应商  1  客户 )，不填默认供应商
                    supplierManage.setLinkMan(vo.getLinkMan());//联系人
                    supplierManage.setLinkPhone(vo.getOfficeTel());//电话
                    supplierManage.setSupplierEmail(vo.getEmail());//邮箱
                    supplierManage.setSupplierSite(vo.getPostAddress());//地址
                    supplierManage.setOrg(vo.getOrg());//组织ID
                    supplierManage.setSid(vo.getId());//ID
                    supplierManage.setMakeDate(vo.getMakeDate().replace('T',' '));//修改日期
                    list.add(supplierManage);
                }
            }else {
                System.out.println("查询ERP单据信息为空！");
                throw new ServiceException(CommonCode.SERVER_INERNAL_ERROR,"查询ERP单据信息为空！");
            }
        }else {
            System.out.println("查询ERP单据信息失败！");
            throw new ServiceException(CommonCode.SERVER_INERNAL_ERROR,"查询ERP单据信息失败！");
        }
        return list;
    }

    public LocalDateTime getStringLocalDateTime(String str){
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime dateTime = LocalDateTime.parse(str.replace('T',' '), formatter);
        return dateTime;
    }


}
